<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="课表模板" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="courscheTempId" >
              <j-dict-select-tag type="list" v-model="model.courscheTempId" dictCode="cou_courseschedule_template cct,cct.coursche_temp_name ,cct.id ,cct.iz_open =1 and cct.iz_delete  =0 order by cct.coursche_temp_no"
                                 placeholder="课表模板" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="学年学期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="schoolYearId">
              <!--              <a-input v-model="model.schoolYearId" placeholder="请输入学年"  ></a-input>-->
              <a-select v-model="model.schoolYearId" placeholder="请选择学年" style="width: 60%"
                        :getPopupContainer="(target) => target.parentNode">
                <a-select-option v-for="item in schoolYearDataList" :key="item.value">{{ item.label }}</a-select-option>
              </a-select>
              <a-select v-model="model.semesterId" placeholder="请输入学期" style="width: 40%"
                        :getPopupContainer="(target) => target.parentNode">
                <a-select-option v-for="item in semesterDataList" :key="item.value">{{ item.label }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="课表编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="courseArrangeCode">
              <a-input v-model="model.courseArrangeCode" placeholder="请输入课表编码"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="课表名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="courseArrangeName">
              <a-input v-model="model.courseArrangeName" placeholder="请输入课表名称"  ></a-input>
            </a-form-model-item>
          </a-col>


          <a-col :span="24">
            <a-form-model-item v-show="false" label="课表类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="courseArrangeTtype">
<!--              <a-input-number v-model="model.courseArrangeTtype" placeholder="请输入课表类型(1:班级(默认);2教室场地 3.老师;4.科目 5:学生;)，课表应用对象类型" style="width: 100%" />-->
              <j-dict-select-tag  type="list" @change="handleChangeObjType" v-model="model.courseArrangeTtype"
                                 dictCode="course_target_obj_ttype" placeholder="请选择课表类型，课表应用对象类型" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="应用班级" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="targetObjId" >
              <j-dict-select-tag type="list" v-model="model.gradeId" @change='changeGradeId'  style='width: 45%' dictCode="cou_grade,grade_name,id"
                                 placeholder="选择所属年级"  />
              <j-dict-select-tag type="list" v-model="model.targetObjId" :dictCode="queryParamSelect.classIdSelect" style='width: 55%'
                                 placeholder="班级(默认)，场地，老师，科目,学生，表示该课表应用对象" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="有无单双周科目" style="width: 150%":labelCol="labelCol" :wrapperCol="wrapperCol" prop="courseArrangeIzSingle">
              <!--              <a-input-number v-model="model.courseArrangeIzSingle" placeholder="请输入单双周标识(1单周（默认），2双周 3三周 4四周)" style="width: 100%" />-->
              <j-dict-select-tag type="list" v-model="model.courseArrangeIzSingle" dictCode="course_arrange_iz_single"
                                 placeholder="请选择单双周标识" style="width: 55%" />
            </a-form-model-item>
          </a-col>
        </a-row>
          <a-row >
          <a-col :span="12">
            <a-form-model-item label="启用日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="openStartTime">
              <j-date placeholder="请选择课表启用开始日期" v-model="model.openStartTime"  style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="停用日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="openStopTime">
              <j-date placeholder="请选择课表启用结束日期(含)" v-model="model.openStopTime"  style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
          <a-row >

          <a-col :span="12">
            <a-form-model-item label="课表状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="courseArrangeStatus">
<!--              <a-input v-model="model.courseArrangeStatus" placeholder="请输入课表状态：(1初始 2预排课 3已排课 4已发布 5已下线 6需重排)"  ></a-input>-->
              <j-dict-select-tag type="list" v-model="model.courseArrangeStatus" dictCode="course_arrange_status"
                                 placeholder="请选择课表状态：(1初始 2预排课 3已排课 4已发布 5已下线 6需重排)" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="是否启用" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="izOpen">
              <j-dict-select-tag type="list" v-model="model.izOpen" dictCode="iz_open" placeholder="" />
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item v-show="false" label="是否删除" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="izDelete">
<!--              <a-input-number v-model="model.izDelete" placeholder="请输入是否删除（0否 1是已删除）" style="width: 100%" />-->
              <j-dict-select-tag type="list" v-model="model.izDelete" dictCode="iz_delete" placeholder="" />
            </a-form-model-item>
          </a-col>
<!--          <a-col :span="24">-->
<!--            <a-form-model-item label="学校编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="tenantId">-->
<!--              <a-input v-model="model.tenantId" placeholder="请输入学校编码"  ></a-input>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
<!--          <a-col :span="24">-->
<!--            <a-form-model-item label="创建时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">-->
<!--              <j-date placeholder="请选择创建时间" v-model="model.createTime"  style="width: 100%" />-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
<!--          <a-col :span="24">-->
<!--            <a-form-model-item label="创建人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createUser">-->
<!--              <a-input v-model="model.createUser" placeholder="请输入创建人"  ></a-input>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
<!--          <a-col :span="24">-->
<!--            <a-form-model-item label="编辑时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="editTime">-->
<!--              <j-date placeholder="请选择编辑时间" v-model="model.editTime"  style="width: 100%" />-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
<!--          <a-col :span="24">-->
<!--            <a-form-model-item label="编辑人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="editUser">-->
<!--              <a-input v-model="model.editUser" placeholder="请输入编辑人"  ></a-input>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
        </a-row>

      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import {
    getAllClass,
    getClassroomDataList,
    getClassStudentQueryAll,
    getSchoolYearDataList, getSemesterDataList,
    getSubjectList,
    getTeacherList
  } from '@api/commonAPI'

  export default {
    name: 'CouCourseArrangeForm',
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model:{
          courseArrangeIzSingle: 1,
          courseArrangeStatus: 1,
          courseArrangeTtype: '1',
          izOpen: 1,
          izDelete: 0,
         },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          courscheTempId:[{ required: true, message: '请选择课表模板!'},],
           semesterId: [
              { required: true, message: '请输入学期!'},
           ],
           schoolYearId: [
              { required: true, message: '请输入学年!'},
           ],
           targetObjId: [
              { required: true, message: '请输入目标对象id(班级id(默认)，场地id，老师id，科目id,学生id)，表示该课表应用对象!'},
           ],
           izOpen: [
              { required: true, message: '请输入是否启用（0否停用，1是启用）!'},
           ],
           izDelete: [
              { required: true, message: '请输入是否删除（0否 1是已删除）!'},
           ],
        },
        //查询条件联动部分定义
        queryParamSelect: {
          classIdSelect: "cou_class,class_name,id,class_iz_open  =1 and class_iz_delete  = 0 order by  class_order",
          classroomIdSelect: "fac_classroom,classroom_name,id",
        },
        url: {
          add: "/coucoursearrange/couCourseArrange/add",
          edit: "/coucoursearrange/couCourseArrange/edit",
          queryById: "/coucoursearrange/couCourseArrange/queryById"
        },
        semesterDataList: [],
        schoolYearDataList: [],
        objectList: [],
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      this.getSchoolYearData();
      this.getSemesterData();
    },
    methods: {
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.model = Object.assign({}, record);
        this.visible = true;
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }

        })
      },
      async getSchoolYearData() {
        let res = await getSchoolYearDataList()
        this.schoolYearDataList = []
        res.result.forEach(item => {
          this.schoolYearDataList.push({
            label: item.schoolYearName,
            value: item.id
          })
        })
      },
      async getSemesterData() {
        let res = await getSemesterDataList()
        this.semesterDataList = []
        res.result.forEach(item => {
          this.semesterDataList.push({
            label: item.semesterName,
            value: item.id
          })
        })
      },
      changeGradeId(){
        this.queryParamSelect.classIdSelect = "cou_class cc,cc.class_name,cc.id,cc.class_iz_open  =1 and cc.class_iz_delete  =0 and cc.grade_code = \'"+this.model.gradeId+"\' order by cc.grade_code !! cc.class_order !! cc.create_time";
      },

      handleChangeObjType() {
        let type = this.model.courseArrangeTtype
        this.objectList = []
        switch (type) {
          case '1':
            this.getClassesList()
            break
          case '2' :
            this.getClassroomList()
            break
          case '3':
            this.getTeacherList()
            break
          case '4':
            this.getSubjectList()
            break
          case '5':
            this.getStudentList()
            break
          default :
            this.$message.error('获取初始化数组出错')
        }
      },
      async getClassesList() {
        let res = await getAllClass()
        if (res.success) {
          res.result.forEach(item => {
            this.objectList.push({
              label: item.className,
              value: item.id
            })
          })
        } else {
          this.$message.error('获取初始化数组出错')
        }
      },
      async getClassroomList() {
        let res = await getClassroomDataList()
        if (res.success) {
          res.result.forEach(item => {
            this.objectList.push({
              label: item.classroomName,
              value: item.id
            })
          })
        } else {
          this.$message.error('获取初始化数组出错')
        }
      },
      async getTeacherList() {
        let res = await getTeacherList()
        if (res.success) {
          res.result.forEach(item => {
            this.objectList.push({
              label: item.teacherName,
              value: item.teacherId
            })
          })
        } else {
          this.$message.error('获取初始化数组出错')
        }
      },
      async getSubjectList() {
        let res = await getSubjectList()
        if (res.success) {
          res.result.forEach(item => {
            this.objectList.push({
              label: item.subjectName,
              value: item.subjectId
            })
          })
        } else {
          this.$message.error('获取初始化数组出错')
        }
      },
      async getStudentList() {
        let res = await getClassStudentQueryAll()
        if (res.success) {
          res.result.forEach(item => {
            this.objectList.push({
              label: item.studentName,
              value: item.id
            })
          })
        } else {
          this.$message.error('获取初始化数组出错')
        }
      },

    }
  }
</script>